package ferp.android.activities.preferences;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import ferp.android.GUI;
import ferp.android.R;
import ferp.android.managers.DeckManager;

/**
 * User: olegs
 * Date: 12/30/13 10:33 PM
 */
public class DeckList extends List
{
  public static void setup(Preferences owner, int key, String deck)
  {
    DeckList preference = owner.find(DeckList.class, key);
    DeckManager dm = DeckManager.instance(owner);
    String[] values = dm.decks();
    String[] entries = new String[values.length];
    String error = dm.error(owner, deck);

    System.arraycopy(values, 0, entries, 0, values.length);
    entries[0] = owner.getString(R.string.settings_deck_standard);

    preference.setEntries(entries);
    preference.setEntryValues(values);

    int selected = preference.findIndexOfValue(deck);

    if (error == null)
      preference.update(selected);
    else
      // the selected value might not be found in case the deck's file was removed from sd card
      if (selected == -1)
        preference.update(deck, error);
      else
        preference.update(selected, error);
  }

  public DeckList(Context context)
  {
    this(context, null);
  }

  public DeckList(Context context, AttributeSet attrs)
  {
    super(context, attrs);
  }

  @Override
  public CharSequence getSummary() {return summary.value;}

  @Override
  public void setSummary(CharSequence summary)
  {
    this.summary.value = summary;

    if (this.summary.tv != null)
      this.summary.tv.setText(summary);
  }

  public void update(String value, String error)
  {
    setValue(value);
    setSummary(GUI.getColoredText(value + "<br>", "red", error));
  }

  public String update(int selected)
  {
    setValue(getEntryValues()[selected].toString());
    setSummary(getEntries()[selected]);

    return getValue();
  }

  public String update(int selected, String error)
  {
    update(getEntryValues()[selected].toString(), error);

    return getValue();
  }

  @Override
  protected void onBindView(View view)
  {
    super.onBindView(view);

    summary.tv = (TextView)view.findViewById(android.R.id.summary);

    if (summary.value != null)
      summary.tv.setText(summary.value);
  }

  private static final class Summary
  {
    private CharSequence value;
    private TextView tv;
  }

  private Summary summary = new Summary();
}
